using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BA2009.Services;
using BA2009.Entities;

namespace BA2009.Web.Controllers
{
   

    public class BannerFormViewModel
    {
        public Banner Banner { get; private set; }

        public SelectList BannerTypes { get; private set; }

        public IList<Resource> Resources { get; private set; }

        public IList<BannerPosition> Positions { get; private set; }

        public BannerFormViewModel(Banner banner,IList<BannerType> bannerTypes,IList<Resource> resources,IList<BannerPosition> positions)
        {
            Banner = banner;
            BannerTypes = new SelectList(bannerTypes,"BannerTypeID","BannerTypeName", banner.BannerTypeID);

            Resources = resources;
            Positions = positions;
        }


    }

    public class BannersController : Controller
    {
        public IBannerService Service
        {
            get;
            private set;
        }

        public BannersController(IBannerService service)
        {
            //if (service == null)
            //    service = new BannerService();
            Service = service;
        }

        //public BannersController()
        //    : this(null)
        //{ }

        
        //
        // GET: /Banners/

        //[Authorize()]

        public ActionResult Index()
        {
            var banners = Service.FindAll();

            
            return View(banners);
        }

        //
        // GET: /Banners/Details/5

        //[Authorize()]
        public ActionResult Details(int id)
        {
            //var banner = objBannerRepository.GetById(id);
            var banner = Service.GetById(id);
            if (banner == null)
                return View("Notfound");
            else
                return View(banner);
        }

        //
        // GET: /Banners/Create

        //[Authorize()]
        public ActionResult Create()
        {
            Entities.Banner banner = new Banner();
            IList<BannerType> bannerTypes = Service.GetAllBannerTypes();

            IList<Resource> resources = Service.GetResources();

            IList<BannerPosition> positions = Service.GetPositions();

            BannerFormViewModel viewModel = new BannerFormViewModel(banner, bannerTypes, resources, positions);

            return View(viewModel);
        } 

        //
        // POST: /Banners/Create

        //[Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create( FormCollection formCollections)
        {
            try
            {

                var keys = formCollections.AllKeys.AsQueryable();

                string code = formCollections.Get("Code");
                string bannerName = formCollections.Get("BannerName");
                int bannerType = Convert.ToInt32(formCollections.Get("BannerTypeID"));

                Banner banner = new Banner
                {
                    Code=code,
                    BannerName=bannerName,
                    BannerTypeID=bannerType
                };

                //int newid = Service.Add(banner);

                // Add data to BannerResource table
                IList<int> checkedIds = this.GetCheckedMaps(keys, "chkResourceID_");
                IList<MapEntity> resources = null;
                if (checkedIds.Count > 0)
                {
                    resources = this.MakeMapEntities(0, checkedIds);
                }

                IList<int> checkedPositionIds = this.GetCheckedMaps(keys, "chkPositionID_");

                IList<MapEntity> positions = null;
                if (checkedPositionIds.Count > 0)
                {
                    positions = this.MakeMapEntities(0, checkedPositionIds);
                }


                object[] maps = new object[] { resources, positions };
                int newId = Service.Add(banner, maps);
                return RedirectToAction("Index");
                
            }
            catch(Exception ex)
            {
                Utility.ExceptionManager.Handle(ex);
                return View();
            }
        }

    
        private IList<MapEntity> MakeMapEntities(int id1,IList<int> id2s)
        {
            IList<MapEntity> ret = new List<MapEntity>();
            foreach (int id2 in id2s)
            {
                var map = new MapEntity { ID1 = id1, ID2 = id2 };
                ret.Add(map);
            }

            return ret;
        }


        private IList<int> GetCheckedMaps(IQueryable<string> keys,string formStartName)
        {
            IList<int> ret = new List<int>();
            var checks = (from k in keys
                          where k.StartsWith(formStartName)
                          select k).ToList();

            if (checks != null && checks.Count > 0)
            {
                for (int i = 0; i < checks.Count; i++)
                {
                    var id = Convert.ToInt32(checks[i].Substring(checks[i].LastIndexOf('_')+1));

                    ret.Add(id);
                }
            }

            return ret;
        }

        //
        // GET: /Banners/Edit/5
 
      
        public ActionResult Edit(int id)
        {
            Banner banner = Service.GetById(id);

            IList<BannerType> bannerTypes = Service.GetAllBannerTypes();

            IList<Resource> resources = Service.GetResources();

            IList<BannerPosition> positions = Service.GetPositions();

            BannerFormViewModel viewModel = new BannerFormViewModel(banner, bannerTypes, resources, positions);

            return View(viewModel);
        }

        //[Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(FormCollection formCollections)
        {
            try
            {

                var keys = formCollections.AllKeys.AsQueryable();

                int id = Convert.ToInt32(formCollections.Get("BannerID"));
                string code = formCollections.Get("Code");
                string bannerName = formCollections.Get("BannerName");
                int bannerType = Convert.ToInt32(formCollections.Get("BannerTypeID"));

                Banner banner = new Banner
                {
                    BannerID=id,
                    Code = code,
                    BannerName = bannerName,
                    BannerTypeID = bannerType
                };

                //int newid = Service.Add(banner);

                // Add data to BannerResource table
                IList<int> checkedIds = this.GetCheckedMaps(keys, "chkResourceID_");
                IList<MapEntity> resources = null;
                if (checkedIds.Count > 0)
                {
                    resources = this.MakeMapEntities(id, checkedIds);
                }
                else
                {
                    resources = new List<MapEntity>();
                    resources.Add(new MapEntity { ID1 = id, ID2 = 0 });
                }

                IList<int> checkedPositionIds = this.GetCheckedMaps(keys, "chkPositionID_");

                IList<MapEntity> positions = null;
                if (checkedPositionIds.Count > 0)
                {
                    positions = this.MakeMapEntities(id, checkedPositionIds);
                }
                else
                {
                    positions = new List<MapEntity>();
                    positions.Add(new MapEntity { ID1 = id, ID2 = 0 });
                }


                object[] maps = new object[] { resources, positions };
                int newId = Service.Update(banner, maps);
                return RedirectToAction("Index");

            }
            catch (Exception ex)
            {
                Utility.ExceptionManager.Handle(ex);
                return View();
            }
        }

        //
        // POST: /Banners/Edit/5

        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult Edit(int id, Banner banner)
        //{
        //    try
        //    {
        //        Service.Update(banner);
        //        return RedirectToAction("Details", new { id = banner.BannerID });
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        //public JsonResult Delete(int id)
        //{
        //    var banner = Service.GetById(id);
        //    Service.Delete(banner);

        //    var banners = Service.FindAll();
        //    return this.Json(banners);
        //}

        //[Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete(int id)
        {
            var banner = Service.GetById(id);
            var ret=Service.Delete(banner);

            return this.Json(ret);
        }
    }
}
